package com.ruoyi.order.config;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.ruoyi.order.domain.VerificationRecord;
import com.ruoyi.order.mapper.VerificationRecordMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Component
@Slf4j
@RequiredArgsConstructor
public class VerificationSchedule {


    private final VerificationRecordMapper verificationRecordMapper;

    @Resource
    private RedisTemplate redisTemplate;


    // 每天凌晨1点执行
    @Scheduled(cron = "0 0 1 * * ?")
    public void expireVerificationCodes() {
        log.info("开始处理过期核销码...");
        Date now = new Date();
        List<VerificationRecord> expiredRecords = verificationRecordMapper.selectExpiredRecords(now);

        for (VerificationRecord record : expiredRecords) {
            try {
                // 更新状态为过期
         record  = new LambdaUpdateWrapper<VerificationRecord>()
                        .set(VerificationRecord::getStatus, 2)
                        .getEntity();
                // 从缓存中删除
                redisTemplate.delete("verify:code:" + record.getVerifyCode());

                log.info("核销码[{}]已标记为过期", record.getVerifyCode());
            } catch (Exception e) {
                log.error("处理过期核销码[{}]失败", record.getVerifyCode(), e);
            }
        }

        log.info("过期核销码处理完成，共处理{}条记录", expiredRecords.size());
    }
}